package com.csii.oauth.filter.exchange.impl;

import cn.hutool.core.bean.BeanUtil;
import com.csii.core.constant.CommonConstant;
import com.csii.core.system.vo.LoginUser;
import com.csii.core.util.TenantContext;
import com.csii.oauth.filter.exchange.IAuthExchange;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Map;

/**
 * @Description TODO
 * @Date 2020/9/16 13:11
 * @Created by Ian
 * @Contact: 19107614@qq.com
 */
@Slf4j
public class HeaderParseExchange implements IAuthExchange {
    @Override
    public void exchange(HttpServletRequest request, HttpServletResponse response) {
        if(SecurityContextHolder.getContext().getAuthentication()!=null &&SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof Map)
        {
            LoginUser userInfo= LoginUser.build((Map)SecurityContextHolder.getContext().getAuthentication().getPrincipal()) ;
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken( userInfo, null, SecurityContextHolder.getContext().getAuthentication().getAuthorities()));
            authTenant(userInfo,request);
        }
    }

    private String getTenantId(HttpServletRequest request){
        String tenantId = request.getHeader(CommonConstant.TENANT_ID);
        return tenantId == null ? request.getParameter(CommonConstant.TENANT_ID):tenantId;
    }

    private boolean authTenant(LoginUser loginUser , HttpServletRequest request ){
        //用户必须要有租户id
        if (StringUtils.isEmpty(loginUser.getRelTenantIds())) {
            return true;
        }
        //获取用户拥有的TenantId
        String[] userTenantIds = loginUser.getRelTenantIds().split(",");

        //获取前端传过来的租户id
        String tenantId = getTenantId(request);
        //如果前端没有传租户ID , 就默认指定一个
        if(tenantId == null){
            tenantId = userTenantIds[0];
        }
        TenantContext.setTenant(tenantId);
        //验证当前用户是否有这个租户ID的权限
        String recordTenantId = tenantId;
        //0 是默认租户,并且是有管理员权限 ,就不需要拦截
        return !Arrays.stream(userTenantIds).filter(orgTenantId -> orgTenantId.equals("0")).findAny().isPresent()
                && !Arrays.stream(userTenantIds).filter(orgTenantId -> orgTenantId.equals(recordTenantId)).findAny().isPresent();
    }

}
